package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.service.WxCouponService;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: MYM
 * @Date: 2024/05/20/20:52
 * @Description:
 */
@RestController
@RequestMapping("/wx/coupon")
public class WxCouponController {
    @Autowired
    WxCouponService wxCouponService;
    @Autowired
    SecurityManager securityManager;

    @GetMapping("/mylist")
    public Object myList(Short status, Integer page, Integer limit) {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        MarketUser user = (MarketUser) subject.getPrincipal();
        return ResponseUtil.okList(wxCouponService.myList(user, status, page, limit), wxCouponService.myListPage(user, status, page, limit));
    }

    @GetMapping("/list")
    public Object list(Integer page, Integer limit) {
        return ResponseUtil.okList(wxCouponService.list(page, limit));
    }

    @GetMapping("/selectlist")
    public Object selectList(Integer cartId, Integer grouponRuleId) {
        return ResponseUtil.okList(wxCouponService.selectList(cartId, grouponRuleId));
    }
    @PostMapping("/receive")
    public Object receive(@RequestBody Map map) {
        Integer couponId = (Integer) map.get("couponId");
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        MarketUser user = (MarketUser) subject.getPrincipal();
        wxCouponService.receive(couponId, user);
        return ResponseUtil.ok(null);
    }
    @PostMapping("/exchange")
    public Object exchange(@RequestBody Map map) {
        String code = (String) map.get("code");
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        MarketUser user = (MarketUser) subject.getPrincipal();
        Object exchange = wxCouponService.exchange(code, user);
        if (exchange == "兑换码不正确") {
            return ResponseUtil.fail(408,"兑换码不正确");
        }
        return ResponseUtil.ok(exchange);
    }
}
